var socket;
function openSocket(){
    if(typeof(WebSocket) == "undefined"){
        console.log("你的浏览器不支持WebSocket")
    }else{
        var socketUrl = "http://192.168.31.145:9000/ws/chat/"+$("#fromUserId").val();
        socketUrl = socketUrl.replace("https","ws").replace("http","ws");
        console.log("socketUrl:"+socketUrl)
    }
    if(socket != null){
        socket.close();
    }
    socket = new WebSocket(socketUrl);
    socket.onopen = function(){
        $("#messageDiv").append("<p>websocket已打开</p>");
    }

    socket.onmessage = function (msg) {
        console.log(msg);
        if(msg.data != "undefined" || msg.data!="" || msg.data!=null){
            $("#messageDiv").append("<p>"+msg.data+"</p>");
        }
    }

    socket.onerror = function () {
        console.log("websocket发生了错误");
    }
}

function sendMessage() {
    if(typeof(WebSocket) == "undefined"){
        console.log("你的浏览器不支持WebSocket")
    }else{
        socket.send('{"fromUserId":"'+$("#fromUserId").val()+'","toUserId":"'+$("#toUserId").val()+'","message":"'+$("#message").val()+'"}');
        $("#messageDiv").append('<p>{"fromUserId":"'+$("#fromUserId").val()+'","toUserId":"'+$("#toUserId").val()+'","message":"'+$("#message").val()+'"}</p>');
    }
}

function closeSocket() {
    console.log("关闭连接");
    socket.close();
}